import axios from "axios";
import { getToken } from "@/composables/cookie";
import { showMessage } from '@/composables/util';
import { useUserStore } from '@/stores/user';

const instance = axios.create({
    baseURL: "/api", // 你的 API 基础 URL
    timeout: 7000, // 请求超时时间
})


//添加请求拦截器
instance.interceptors.request.use(function (config) {
    const token = getToken()
    console.log('统一添加请求头中Token:' + token)

    //当token不为空
    if (token) {
        //添加请求头  key Authorization  value  前缀 Brarer
        config.headers['Authorization'] = 'Bearer ' + token
    }
    
    return config;
}, function (error) {
    return Promise.reject(error)
});

//添加响应拦截器
instance.interceptors.response.use(function (response) {

    return response.data
    
}, function (error) {

    let status = error.response.status

    //状态码401
    if (status == 401) {
        
        let userStore = useUserStore()
        userStore.logout()
        // 刷新页面
        location.reload()
    }



    let errorMsg = error.response.data.message || '请求失败'

    showMessage(errorMsg, "error")
    
    return Promise.reject(error)
})


export default instance;